<?php

declare ( strict_types = 1 )
;

namespace UntilDistributed;

use Exception;

/**
 * 日志处理类
 */
class Log {
	private static $obj = null;
	private $logDir = '/tmp/trans/';
	private $logFile = 'default.log';
	
	private function __construct() {
		$config = ConfigHelper::get ( 'log' );
		if (isset ( $config ['log_dir'] )) {
			$this->logDir = $config ['log_dir'];
		}
		if (isset ( $config ['log_file'] )) {
			$this->logFile = $config ['log_file'];
		}
		
		if (! file_exists ( $this->logDir )) {
			mkdir ( $this->logDir );
			chmod ( $this->logDir, 0755 );
		}
		$this->logFile .= date ( 'Y-m-d' ) . '.log';
	}
	
	/**
	 * [getInstance description]
	 *
	 * @return Log
	 */
	public static function getInstance(): self {
		if (! ( self::$obj instanceof self)) {
			self::$obj = new Log ();
		}
		
		return self::$obj;
	}
	/**
	 *
	 * @param unknown $format
	 * @param unknown $log
	 * @throws Exception
	 * @return bool
	 */
	public function writeLog(string $format, $log): bool {
		$filename = $this->logDir . $this->logFile;
		if (! $fp = fopen ( $filename, 'ab' )) {
			throw new Exception ( 'cant open logfile', 10001 );
		}
		chmod ( $filename, 0755 );
		
		$time_format = date ( 'Y-m-d H:i:s' );
		if (is_array ( $log ) || is_string ( $log )) {
			$log = json_encode ( $log );
		}
		flock ( $fp, LOCK_EX );
		fwrite ( $fp, "$time_format $format {$log}\n" );
		flock ( $fp, LOCK_UN );
		fclose ( $fp );
		
		return true;
	}
	public function error($log) :bool{
		$format = 'Error';
		return $this->writeLog ( $format, $log );
	}
	public function info($log): bool {
		$format = 'Info';
		return $this->writeLog ( $format, $log );
	}
	public function warn($log): bool {
		$format = 'Warning';
		return $this->writeLog ( $format, $log );
	}
}